package ru.acme.lab14.service.command;

import ru.acme.lab14.domain.bank.Bank;
import ru.acme.lab14.domain.client.Client;
import ru.acme.lab14.service.bank.BankService;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.text.ParseException;
import java.util.Scanner;

public class CommandHandler implements Runnable {
	private Bank bank;
	private boolean isLocal;
	private InputStream inputStream;
	private OutputStream outputStream;

	public CommandHandler(Bank bank, boolean isLocal, InputStream inputStream, OutputStream outputStream) {
		this.bank = bank;
		this.isLocal = isLocal;
		this.inputStream = inputStream;
		this.outputStream = outputStream;
	}

	public void run() {
		Scanner scanner = new Scanner(inputStream);
		PrintStream outputPrintStream = new PrintStream(outputStream);
		while (scanner.hasNext()) {
			String command = scanner.nextLine();
			if (command.equals("exit")) {
				break;
			}
			if ((command.length() >= 3) && (command.substring(0, 3).equals("add"))) {
				try {
					BankService.addClient(bank, Client.parseClient(command.substring(4)));
				} catch (ParseException e) {
					outputPrintStream.println("Bad client description");
				}
				continue;
			}
			if ((command.length() >= 5) && (command.substring(0, 5).equals("print"))) {
				for (Client client : bank.getClients()) {
					outputPrintStream.println(client.toString());
				}
				continue;
			}
			outputPrintStream.println("Bad command");
		}
		outputPrintStream.println("Bye!");
		if (isLocal) {
			System.exit(0);
		}
		try {
            // XXX [MY] If 'inputStream.close()' throws exception outputStream will no be closed.
			inputStream.close();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
}
